<template>
  <div class="relative">
    <button @click="toggleDropdown" class="relative p-2 text-gray-700 hover:text-gray-900 transition-colors">
      <BellIcon class="h-6 w-6" />
      <span v-if="unreadCount > 0"
            class="absolute top-0 right-0 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">
        {{ unreadCount > 99 ? '99+' : unreadCount }}
      </span>
    </button>
    
    <!-- 下拉通知列表 -->
    <transition name="dropdown">
      <div v-if="showDropdown" class="absolute right-0 mt-2 w-80 bg-white rounded-2xl shadow-xl z-50 border border-gray-200">
        <div class="p-6 border-b border-gray-100">
          <div class="flex justify-between items-center">
            <h3 class="text-lg font-light text-gray-900">通知</h3>
            <Link href="/notifications" class="text-sm font-medium text-gray-900 bg-gray-100 px-3 py-1 rounded-xl hover:bg-gray-200 transition-colors">查看全部</Link>
          </div>
        </div>
        <div class="max-h-96 overflow-y-auto">
          <div v-for="notification in recentNotifications" :key="notification.id"
               class="p-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors"
               :class="{ 'bg-blue-50': !notification.read_at }"
               @click="handleNotificationClick(notification)">
            <h4 class="font-medium text-sm text-gray-900">{{ notification.data.title }}</h4>
            <p class="text-sm text-gray-600 mt-1 leading-relaxed">{{ notification.data.content }}</p>
            <span class="text-xs text-gray-500 mt-2 block">{{ formatDate(notification.created_at) }}</span>
          </div>
          <div v-if="recentNotifications.length === 0" class="p-8 text-center text-gray-500">
            <svg class="mx-auto h-8 w-8 text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-5 5-5-5h5v-5a7.5 7.5 0 1 0-15 0v5h5l-5 5-5-5h5v-5a7.5 7.5 0 1 0 15 0v5z" />
            </svg>
            <p class="text-sm">暂无新消息</p>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Link, router } from '@inertiajs/vue3'
import { BellIcon } from '@heroicons/vue/24/outline'

const showDropdown = ref(false)
const unreadCount = ref(0)
const recentNotifications = ref([])

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 切换下拉菜单
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value
  if (showDropdown.value) {
    loadRecentNotifications()
  }
}

// 加载最近的通知
const loadRecentNotifications = async () => {
  try {
    const response = await fetch(route('notifications.recent'))
    const data = await response.json()
    recentNotifications.value = data.notifications || []
  } catch (error) {
    console.error('加载通知失败:', error)
  }
}

// 处理通知点击
const handleNotificationClick = (notification) => {
  // 标记为已读
  if (!notification.read_at) {
    router.post(route('notifications.mark-as-read'), {
      ids: [notification.id]
    }, {
      preserveState: true,
      onSuccess: () => {
        // 更新本地状态
        notification.read_at = new Date().toISOString()
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
    })
  }
  
  // 跳转到详情页面
  if (notification.data.action_url) {
    router.visit(notification.data.action_url)
  }
  
  showDropdown.value = false
}

// 加载未读数量
const loadUnreadCount = async () => {
  try {
    const response = await fetch(route('notifications.unread-count'))
    const data = await response.json()
    unreadCount.value = data.count
  } catch (error) {
    console.error('加载未读数量失败:', error)
  }
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event) => {
  if (!event.target.closest('.relative')) {
    showDropdown.value = false
  }
}

onMounted(() => {
  loadUnreadCount()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.dropdown-enter-active, .dropdown-leave-active {
  transition: all 0.2s ease;
}

.dropdown-enter-from, .dropdown-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
